package com.power.using.sharlockchat.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.power.using.sharlockchat.interfaces.ClickItem;
import com.power.using.sharlockchat.view.spinerwindow.AbstractSpinerAdapter;
import com.power.using.sharlockchat.view.spinerwindow.CustemObject;
import com.power.using.sharlockchat.view.spinerwindow.CustemSpinerAdapter;
import com.power.using.sharlockchat.view.spinerwindow.SpinerPopWindow;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.ContentValues.TAG;

/**
 * sometimes I believe compiler ignores all my comments
 * Created by gyyak46 on 2017/3/10.
 */

public class Util {

    /**
     * 检测Sdcard是否存在
     *
     * @return
     */
    public static boolean isExitsSdcard() {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 选择图片裁剪
     *
     * @param
     */
    public static void startImagePick(Activity activity, int flag) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        activity.startActivityForResult(Intent.createChooser(intent, "选择图片"),
                flag);
    }

    /**
     * 相机拍照
     *
     * @param activity
     * @param output   相册拍照存储图片的URI
     * @param flag     标识
     */
    public static void startActionCamera(Activity activity, Uri output, int flag) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
        activity.startActivityForResult(intent, flag);
    }

    /**
     * 拍照后裁剪
     *
     * @param activity
     * @param data     原始图片
     * @param output   裁剪后图片
     * @param crop     裁剪大小
     * @param flag     标识
     */
    public static void startActionCrop(Activity activity, Uri data, Uri output,
                                       int crop, int flag) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        intent.putExtra("output", output);
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", crop);// 输出图片大小
        intent.putExtra("outputY", crop);
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        activity.startActivityForResult(intent, flag);
    }


    // public static void Share(Context context, String Title, String content,
    // String path,String imagePath) {
    // ShareSDK.initSDK(context);
    // OnekeyShare oks = new OnekeyShare();
    // // 关闭sso授权
    // oks.disableSSOWhenAuthorize();
    // // 分享时Notification的图标和文字
    // oks.setNotification(R.drawable.lh_logo, context.getResources()
    // .getString(R.string.app_name));
    // // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
    // oks.setTitle(Title);
    // // text是分享文本，所有平台都需要这个字段
    // oks.setText(content);
    // // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
    // // oks.setImagePath("/storage/emulated/0/picture/default_.jpg");//
    // 确保SDcard下面存在此张图片
    // oks.setImagePath(imagePath);// 确保SDcard下面存在此张图片
    //
    // // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
    // oks.setTitleUrl(path);
    // // url仅在微信（包括好友和朋友圈）中使用
    // oks.setUrl(path);
    // // comment是我对这条分享的评论，仅在人人网和QQ空间使用oks.setComment("我是测试评论文本");
    //
    // // site是分享此内容的网站名称，仅在QQ空间使用
    // oks.setSite(context.getResources().getString(R.string.app_name));
    // // siteUrl是分享此内容的网站地址，仅在QQ空间使用
    // oks.setSiteUrl(path);
    //
    // oks.setSilent(false);
    // oks.setDialogMode();// 显示为弹窗效果
    // // oks.setTheme(OnekeyShareTheme.SKYBLUE);蓝色主题
    // // 启动分享GUI
    // oks.show(context);
    // }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
        /*
         * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
		 * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
		 * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
		 */
        String telRegex = "[1][3587]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) {
            return false;
        } else {

            return mobiles.matches(telRegex);
        }
    }

    public static int getVerCode(Context context) {
        int verCode = -1;
        try {
            verCode = context.getPackageManager().getPackageInfo(
                    "com.myapp", 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
        return verCode;
    }

    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(
                    "com.myapp", 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
        return verName;
    }

//    public  static String getSecondaryStoragePath(Context context) {
//        try {
//            StorageManager sm = (StorageManager) context.getSystemService(STORAGE_SERVICE);
////            Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", null);
////            String[] paths = (String[]) getVolumePathsMethod.invoke(sm, null);
//            // second element in paths[] is secondary storage path
////                    paths[1];
//            return null;
//        } catch (Exception e) {
//            Log.e(TAG, "getSecondaryStoragePath() failed", e);
//        }
//        return null;
//    }

//    public static boolean isSDMounted(Context context) {
//        boolean isMounted = false;
//        StorageManager sm = (StorageManager) context.getSystemService(STORAGE_SERVICE);
//
//        try {
//            Method getVolumList = StorageManager.class.getMethod("getVolumeList", null);
//            getVolumList.setAccessible(true);
//            Object[] results = (Object[])getVolumList.invoke(sm, null);
//            if (results != null) {
//                for (Object result : results) {
//                    Method mRemoveable = result.getClass().getMethod("isRemovable", null);
//                    Boolean isRemovable = (Boolean) mRemoveable.invoke(result, null);
//                    if (isRemovable) {
//                        Method getPath = result.getClass().getMethod("getPath", null);
//                        String path = (String) mRemoveable.invoke(result, null);
//                        Method getState = sm.getClass().getMethod("getVolumeState", String.class);
//                        String state = (String)getState.invoke(sm, path);
//                        if (state.equals(Environment.MEDIA_MOUNTED)) {
//                            isMounted = true;
//                            break;
//                        }
//                    }
//                }
//            }

//            Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", null);
//            String[] paths = (String[]) getVolumePathsMethod.invoke(sm, null);
//            // second element in paths[] is secondary storage path
//            Method getVolumeStateMethod = StorageManager.class.getMethod("getVolumeState", new Class[] {String.class});
//            String state = (String) getVolumeStateMethod.invoke(sm, paths[1]);
//            if (state.equals(Environment.MEDIA_MOUNTED))
//            {
//                isMounted = true;
//
//            }
//        } catch (NoSuchMethodException e){
//            e.printStackTrace();
//        } catch (IllegalAccessException e){
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        }
//
//        return isMounted;
//    }

    /*
    *
    * 获取指定文件的大小
    * */
    public static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    /**
     * popupwindow展示列表
     *
     * @param context
     * @param list
     * @param parentView
     * @param request
     */
    public static void showPopWindow(Context context, List<CustemObject> list, View parentView, final ClickItem request) {

        CustemSpinerAdapter mAdapter = new CustemSpinerAdapter(context);
        mAdapter.refreshData(list, 0);
        SpinerPopWindow spinerPop = new SpinerPopWindow(context);
        spinerPop.setAdatper(mAdapter);

        spinerPop.setWidth(parentView.getWidth());
        spinerPop.showAsDropDown(parentView, 0, -parentView.getHeight());
//        spinerPop.showAsDropDown(parentView);
        spinerPop.setItemListener(new AbstractSpinerAdapter.IOnItemSelectListener() {
            @Override
            public void onItemClick(int pos) {
                request.clickPostion(pos);
            }
        });

    }

    /**
     * 将中文标点替换为英文标点
     *
     * @return 替换后的文本
     */
    public static String replacePunctuation(String text) {
        if (TextUtils.isEmpty(text)) {
            return " ";
        } else {
            text = text.replace('，', ',').replace('。', '.').replace('【', '[').replace('】', ']')
                    .replace('？', '?').replace('！', '!').replace('（', '(').replace('）', ')').replace
                            ('“', '"').replace('”', '"');
            return text;
        }
    }

    /**
     * 获取用户信息
     *
     * @return
     */
//    public static UserInforEntity getUserInforEntity() {
//
//        UserInforEntity userInforEntity = MyApplication.getUserInforEntity();
//        if (userInforEntity == null) {
//            try {
//                userInforEntity = SPUtil.getBeanValue(Constant.KEY_USER, UserInforEntity.class);
//                if (userInforEntity != null) {
//                    MyApplication.setUserInforEntity(userInforEntity);
//                    return userInforEntity;
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                Log.e("显示", "获取userInfor错误");
//            }
//
//        } else {
//            return userInforEntity;
//        }
//        return null;
//    }

    /**
     * 检测是否需要右对齐
     *
     * @param view
     * @param content
     */
    public static void checkLinefeed(TextView view, String content) {
        if (content.length() > 0) {

            double width = view.getWidth();
            double text = view.getPaint().measureText(content);
            if (text > width) {//换行
                view.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
            } else {
                view.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
            }
        }
    }

    /**
     * 获取资质证件
     *
     * @param msg
     * @return
     */
    public static String getQuaValDue(String msg) {
        StringBuilder sb = new StringBuilder();
//        Pattern pattern = Pattern.compile("<b.*?>(.*?)</b>");
        Pattern pattern = Pattern.compile("(?<=\\<b>)(.+?)(?=\\<\\/b>)");
        Matcher matcher = pattern.matcher(msg);
        boolean b = matcher.find(0);
        Log.e("显示", " 是 " + b);
        if (b) {
            Matcher matche = pattern.matcher(msg);
            int i = 0;
            while (matche.find()) {
                if (i == 0) {
                    sb.append(matche.group());
                } else {
                    sb.append("\n" + matche.group());
                }
                i++;
            }
        } else {
            if (msg.length() > 0) {
                sb.append(msg);
            }
        }
        return sb.toString();

    }


    /**
     * 获取资质信息
     *
     * @param msg
     * @return
     */
    public static String getQuaValTitle(String msg) {
        String[] split = msg.split("\\:");
        if (split.length > 0) {
            String s = split[0];
            if (s.contains("过期")) {
                return "以下资质过期";
            }
            if (s.contains("缺少")) {
                return "缺少以下资质";
            }
        }
        return "标题";
    }

    /**
     * 旋转箭头
     *
     * @param image
     */
    public static void openImageView(ImageView image) {
        RotateAnimation animation = new RotateAnimation(0, 180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(700);
        animation.setFillAfter(true);
        image.startAnimation(animation);

    }


    /**
     * 旋转箭头
     *
     * @param image
     */
    public static void closeImageView(ImageView image) {
        RotateAnimation animation = new RotateAnimation(180, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(700);
        animation.setFillAfter(true);
        image.startAnimation(animation);
    }


    /**
     * 打开窗口
     *
     * @param view
     */
    public static void openView(View view) {
        TranslateAnimation mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mShowAction.setDuration(700);
        view.startAnimation(mShowAction);
        view.setVisibility(View.VISIBLE);
    }

    /**
     * 关闭窗口
     *
     * @param view
     */
    public static void clossView(final View view) {
        AlphaAnimation mHiddenAction = new AlphaAnimation(1, 0);
        mHiddenAction.setDuration(700);
        view.startAnimation(mHiddenAction);
        mHiddenAction.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.setVisibility(View.GONE);

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

//        mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
//                0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
//                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
//                -1.0f);
//        mHiddenAction.setDuration(1000);
//        view.startAnimation(mHiddenAction);
//        view.setVisibility(View.GONE);

    }


    /**
     * 检验是否存在小数位
     *
     * @param aFloat
     * @param hintUnit
     */
    public static String checkExitsDecimals(Float aFloat, String hintUnit) {
        Float hintAmount;
        switch (hintUnit) {
            case "吨":
                hintAmount = aFloat / 1000000;
                break;
            case "千克":
                hintAmount = aFloat / 1000;
                break;
            default:
                //升
                hintAmount = aFloat / 1000;
        }
        int bInt = (int) hintAmount.floatValue();
        //System.out.println(" 前"+aFloat+"转换后的数据"+bInt);
        if (bInt == hintAmount) {
            LogUtils.e("bint", "bint " + bInt);
            return bInt + " " + hintUnit;
        } else {
            DecimalFormat df = new DecimalFormat("0.0000");
            LogUtils.e("afloat", "aFloat " + aFloat + " " + df.format(hintAmount));
            return df.format(hintAmount) + " " + hintUnit;
        }

    }

    /** 将小数处理后改为String
     * @param aFloat
     * @param hintUnit
     * @return
     */
    public static String decimals2String(Float aFloat, String hintUnit) {
        Float hintAmount;
        if (aFloat == null && hintUnit == null) {
            return "0";
        }
        switch (hintUnit) {
            case "吨":
                hintAmount = aFloat / 1000000;
                break;
            case "千克":
                hintAmount = aFloat / 1000;
                break;
            default:
                //升
                hintAmount = aFloat / 1000;
        }

        DecimalFormat df = new DecimalFormat("0.0000");
        LogUtils.e("afloat", "aFloat " + hintAmount + " " + df.format(hintAmount));
        return df.format(hintAmount) + hintUnit;
    }

    public static void main(String[] ard) {
        //checkExitsDecimals(123.00f,"cudn");

        Float flaot = 100f;

        // System.out.println("xianshi 数字 "+flaot/1000000);
        DecimalFormat df = new DecimalFormat("0.0000");

        System.out.println("xianshi  " + df.format(flaot / 1000000));
    }

}
